package cn.cs.controller;

import cn.cs.config.WXPayConfig;
import cn.cs.pojo.WxAccessToken;
import cn.cs.util.TenpayUtil;
import cn.cs.util.WeiXinUtil;
import cn.cs.util.WxAccessTokenUtils;
import net.sf.json.JSONObject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.Map;

@RequestMapping("/cs_pay/wxSaoYiSao")
@Controller
public class WxSaoYiSaoController {
    @Resource
    private WXPayConfig wxPayConfig;
    @Resource
    private WxAccessTokenUtils wxAccessTokenUtils;
    /**
     *微信扫一扫接口
     *
     * @author yuexl
     * @param request
     * @throws Exception
     * @version 1.0
     */
    @RequestMapping(value="getWechatSign", method = RequestMethod.GET)
    public @ResponseBody
    Map<String, Object> getWechatSign(HttpServletRequest request) throws Exception {
        /* 返回的json数据 */
        Map<String, Object> jsonMap = new HashMap<String, Object>();
        // 1.获取参数
        String url = request.getParameter("url");
        String appId =wxPayConfig.getAppID();
        String appSecret = wxPayConfig.getAppSecret();
        if (url == null) {
            return jsonMap;
        } else {
            WxAccessToken wxAccessToken =  wxAccessTokenUtils.getWxAccessTokenOf2();
//            String  accessToken =getAccessToken(appId, appSecret);
            String accessToken = wxAccessToken.getAccessToken();
            String ticket = getTicket(accessToken);
            Long timestamp = System.currentTimeMillis() / 1000;
            String nonceStr = getNonceStr();
            String sign = getSign(ticket, nonceStr, timestamp, url);
            jsonMap.put("result", "1");
            jsonMap.put("timestamp", timestamp);
            jsonMap.put("nonceStr", nonceStr);
            jsonMap.put("appId", appId);
            jsonMap.put("sign", sign);
        }
        return jsonMap;
    }



    /**
     * 获取微信ticket<BR>
     *
     * @author yuexl
     * @param token
     * @return
     * @version 1.0
     */
    public static String getTicket(String token) {
        if ("".equalsIgnoreCase(token) || null == token) {
            return "";
        }
        String ticket_url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=" + token + "&type=jsapi";
        JSONObject result = WeiXinUtil.httpRequest(ticket_url, "POST",null);
        return result.get("ticket").toString();

    }
    /**
     * 获取微信签名<BR>
     *
     * @author yuexl
     * @param jsapi_ticket,noncestr随机数，timestamp,url
     * @return
     * @version 1.0
     */
    public static String getSign(String jsapi_ticket, String noncestr, Long timestamp, String url)
            throws NoSuchAlgorithmException {
        String shaStr = "jsapi_ticket=" + jsapi_ticket + "&noncestr=" + noncestr + "&timestamp=" + timestamp + "&url="
                + url;
        MessageDigest mDigest = MessageDigest.getInstance("SHA-1");
        byte[] result = mDigest.digest(shaStr.getBytes());
        StringBuffer signature = new StringBuffer();
        for (int i = 0; i < result.length; i++) {
            signature.append(Integer.toString((result[i] & 0xff) + 0x100, 16).substring(1));
        }
        return signature.toString();
    }
    /**
     * 获取随机字符串
     * @author yuexl
     * @return
     */
    public static String getNonceStr() {
        // 随机数
        String currTime = TenpayUtil.getCurrTime();
        // 8位日期
        String strTime = currTime.substring(8, currTime.length());
        // 四位随机数
        String strRandom = TenpayUtil.buildRandom(4) + "";
        // 10位序列号,可以自行调整。
        return strTime + strRandom;
    }


}
